package com.snail.billing.net;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;

public abstract class BillingDataInfoHttpSession extends BillingHttpSession {

	@Override
	public void buildParamPair() {
		BillingSecurity security = getSecurity();
		String dataInfo = buildDataInfo(getBillingPairList());
		addParamPair("dataInfo", dataInfo);
		String securityInfo = bulidSecurityInfo(security, dataInfo);
		addParamPair("securityInfo", securityInfo);
	}

	protected String buildDataInfo(final List<NameValuePair> list) {
		List<String> tempList = new ArrayList<String>();
		for (NameValuePair pair : list) {
			tempList.add(pair.getName());
			tempList.add(pair.getValue());
		}
		return bulidJson(tempList);
	}

	protected String bulidSecurityInfo(BillingSecurity security, String dataInfo) {
		String origin = security.accessId + security.accessPasswd + security.accessType + dataInfo + JSON + security.seed;
		List<String> tempList = new ArrayList<String>();
		tempList.add("accessId");
		tempList.add(security.accessId);
		tempList.add("accessPasswd");
		tempList.add(security.accessPasswd);
		tempList.add("accessType");
		tempList.add(security.accessType);
		tempList.add("returnType");
		tempList.add(JSON);
		tempList.add("verifyStr");
		tempList.add(BillingEncode.MD5(origin));
		return bulidJson(tempList);
	}

	protected String bulidJson(List<String> paramsList) {
		if (paramsList == null || paramsList.size() == 0) {
			return "";
		}
		StringBuilder builder = new StringBuilder();
		builder.append("{");
		for (int i = 0; i < paramsList.size(); i += 2) {
			String key = paramsList.get(i);
			String value = paramsList.get(i + 1);
			if (i != 0) {
				builder.append(",");
			}
			builder.append("\"").append(key).append("\":\"").append(value).append("\"");
		}
		builder.append("}");
		return builder.toString();
	}

}
